package com.coocaa.x.service.litecontent.providers.store.host.com_coocaa_theme;


import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.FileUtils;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.Storage;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.BroadcastAction;
import com.coocaa.x.service.litecontent.LiteContentProvider;
import com.coocaa.x.service.litecontent.LiteContentProvider.LiteContentProviderHost;
import com.coocaa.x.service.litecontent.LiteContentProvider.ResourceHandler;
import com.coocaa.x.service.litecontent.data.ResultPackage;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_Boolean;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperCategory;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperCategory.WallPaper_Category_Item;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperList;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperList.WallPaper_Item;
import com.coocaa.x.service.litecontent.providers.store.host.com_coocaa_theme.data.Wallpaper;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.WallpaperBean;
import com.skyworth.webSDK.webservice.tcappstore.WallpaperCategoryBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StoreHost_Com_Coocaa_WallPaper extends LiteContentProviderHost implements Storage.IStorageListener {
    private static final String tag = "wallpaper";
    private static StoreHost_Com_Coocaa_WallPaper instance = null;
    private static final String FILE_PRE = "file://";
    private static final String MYCOLLECTION = "mycollection";
    private static final String OWNWALLPAPER = "ownwallpaper";
    private static final String AllWALLPAPER = "allwallpaper";
    private Map<String, Wallpaper> collectionMap = new HashMap<String, Wallpaper>();
    private List<WallPaper_Item> ownWallPaperList = new ArrayList<WallPaper_Item>();

    public static synchronized void create(Context context, LiteContentProvider provider) {
        if (instance == null) {
            instance = new StoreHost_Com_Coocaa_WallPaper(context, provider);
            Storage.addListener(instance);
        }
    }

    private static final String MY_HOST = "com.coocaa.theme";

    private StoreHost_Com_Coocaa_WallPaper(Context context, LiteContentProvider provider) {
        super(context, provider);
    }

    @Override
    public String myHost() {
        return MY_HOST;
    }

    private ResourceHandler wallpaper_category = new ResourceHandler(this, "/wallpaper/category") {
        private List<WallPaper_Category_Item> getWallpaperCategory() {
            List<WallPaper_Category_Item> list = new ArrayList<WallPaper_Category_Item>();
            LogUtils.d(tag, "getWallpaperCategory  collection size:" + collectionMap.size() + " ownWallPaperList.size():" + ownWallPaperList.size());
            WallPaper_Category_Item collectionItem = new WallPaper_Category_Item(MYCOLLECTION, "", "我的收藏", collectionMap.size());
            WallPaper_Category_Item ownItem = new WallPaper_Category_Item(OWNWALLPAPER, "", "自定义壁纸", ownWallPaperList.size());
            list.add(ownItem);
            list.add(collectionItem);

            boolean NetConnected = Android.isNetConnected(CoocaaApplication.getContext());
            LogUtils.d(tag, "getWallpaperCategory NetConnected:" + NetConnected);
            if (NetConnected) {
                //从后台拿数据
                try {
                    List<WallpaperCategoryBean> beanList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getWallpaperCatrgoryList();
                    if (beanList != null && beanList.size() > 0) {
                        LogUtils.d(tag, "getWallpaperCategory size:" + beanList.size());
                        for (WallpaperCategoryBean bean : beanList) {
//                            LogUtils.d(tag, "getWallpaperCategory titel:" + bean.getTitle() + " id:" + bean.getCategoryId() + " total:" + bean.getTotal());
                            WallPaper_Category_Item onlineItem = new WallPaper_Category_Item(String.valueOf(bean.getCategoryId()), bean.getIconUrl(), bean.getTitle(), bean.getTotal());
                            list.add(onlineItem);
                        }
                    }
                } catch (AppStoreException e) {
                    LogUtils.d(tag, "getWallpaperCategory error");
                    e.printStackTrace();
                }
            } else {
                WallPaper_Category_Item allItem = new WallPaper_Category_Item(AllWALLPAPER, "", "全部壁纸", 0);
                list.add(allItem);
            }
            LogUtils.d(tag, "getWallpaperCategory 22 size:" + list.size());
            return list;
        }

        @Override
        public ResultPackage call(Uri uri) {
            if (collectionMap.size() < 1) {
                initCollectionMap();
            }
            initOwnWallPaperList();
            LogUtils.d(tag, "getWallpaperCategory  call  uri:" + uri.toString());
            RP_WallpaperCategory rp = new RP_WallpaperCategory();
            List<WallPaper_Category_Item> list = getWallpaperCategory();
            LogUtils.d(tag, "getWallpaperCategory  call  size:" + (list == null));
            if (list != null && list.size() > 0) {
                LogUtils.d(tag, "getWallpaperCategory  call  size:" + list.size());
                for (WallPaper_Category_Item item : list)
                    rp.resource.add(item);
            }
            return rp;
        }
    };

    private ResourceHandler wallpaper_list = new ResourceHandler(this, "/wallpaper/list") {

        private List<WallPaper_Item> getWallpaperListForOwn(String index, String count) {
            List<WallPaper_Item> list = new ArrayList<WallPaper_Item>();
            LogUtils.d(tag, "getWallpaperListForOwn  index:" + index + " count:" + count);
            synchronized (ownWallPaperList) {
                if (ownWallPaperList != null && ownWallPaperList.size() > 0) {
                    int listSize = ownWallPaperList.size();
                    int i = Integer.parseInt(index) + 1;
                    int c = Integer.parseInt(count);
                    LogUtils.d(tag, "getWallpaperListForOwn  size:" + listSize + "  i*c:" + i * c);
                    if (listSize <= i * c)
                        list = ownWallPaperList.subList((i - 1) * c, listSize);
                    else
                        list = ownWallPaperList.subList((i - 1) * c, i * c);
                }
            }
            return list;
        }

        private synchronized List<WallPaper_Item> getWallpaperListForCollection(String index, String count) {
            List<WallPaper_Item> list = new ArrayList<WallPaper_Item>();
            LogUtils.d(tag, "getWallpaperListForCollection  index:" + index + " count:" + count);
            try {
                Wallpaper wallpaper = new Wallpaper();
                List<LiteDBSupport> wList = wallpaper.selectAll();
                if (wList != null && wList.size() > 0) {
                    int listSize = wList.size();
                    int i = Integer.parseInt(index) + 1;
                    int c = Integer.parseInt(count);
                    LogUtils.d(tag, "getWallpaperListForCollection  size:" + listSize + "  i*c:" + i * c);
                    if (listSize <= i * c)
                        wList = wList.subList((i - 1) * c, listSize);
                    else
                        wList = wList.subList((i - 1) * c, i * c);

                    for (LiteDBSupport db : wList) {
                        Wallpaper w = (Wallpaper) db;
                        list.add(new WallPaper_Item(w.id, w.name, w.type, w.isCollected, w.bigUrl, w.smallUrl));
                    }
                }
            } catch (Exception e) {
                LogUtils.d(tag, "getWallpaperListForCollection  error  ");
                e.printStackTrace();
            }
            LogUtils.d(tag, "getWallpaperListForCollection 22 size:" + list.size());
            return list;
        }

        private List<WallPaper_Item> getWallpaperListForOnline(String id, String index, String count) {
            LogUtils.d(tag, "getWallpaperListForOnline  id:" + id);
            List<WallPaper_Item> list = new ArrayList<WallPaper_Item>();
            try {
                String realIndex = String.valueOf(Integer.parseInt(index) + 1);
                List<WallpaperBean> beanList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getWallpaperList(id, realIndex, count);
                if (beanList != null && beanList.size() > 0) {
                    for (WallpaperBean bean : beanList) {
//                        LogUtils.d(tag,"getWallpaperListForOnline bean id:"+bean.getId()+" name:"+bean.getName());
                        WallPaper_Item item1 = new WallPaper_Item(String.valueOf(bean.getId()), bean.getName(), id, false, bean.getBigUrl(), bean.getSmallUrl());
                        if (collectionMap.containsKey(item1.id))
                            item1.isCollected = true;
                        list.add(item1);
                    }
                }
            } catch (AppStoreException e) {
                e.printStackTrace();
            }
//            list = getTestWllPaperList();
            LogUtils.d(tag, "getWallpaperListForOnline size:" + list.size());
            return list;
        }

        private List<WallPaper_Item> getWallpaperList(String id, String index, String count) {
            List<WallPaper_Item> list = new ArrayList<WallPaper_Item>();
            if (id.equals(MYCOLLECTION)) {
                list = getWallpaperListForCollection(index, count);   //收藏壁纸
            } else if (id.equals(OWNWALLPAPER)) {
                list = getWallpaperListForOwn(index, count);          //自定义壁纸
            } else {
                //从后台拿数据
                list = getWallpaperListForOnline(id, index, count);
            }
            return list;
        }

        @Override
        public ResultPackage call(Uri uri) {
            LogUtils.d(tag, "getWallpaperList   uri:" + uri.toString());
            String id = uri.getQueryParameter("id");
            String index = uri.getQueryParameter("index");
            String count = uri.getQueryParameter("count");
            LogUtils.d(tag, "getWallpaperList   id:" + id + " index:" + index + " count:" + count);
            RP_WallpaperList rp = new RP_WallpaperList();
            if (id != null && !id.equals("")) {
                List<WallPaper_Item> list = getWallpaperList(id, index, count);
                if (list != null && list.size() > 0) {
                    for (WallPaper_Item item : list)
                        rp.resource.add(item);
                }
            }
            return rp;
        }
    };

    private ResourceHandler wallpaper_collection = new ResourceHandler(this, "/wallpaper/collection") {

        private boolean addCollection(String param) {
            WallPaper_Item item = WallPaper_Item.parseJObject(param, WallPaper_Item.class);
            LogUtils.d(tag, "addCollection name:" + item.name + " url:" + item.bigUrl + "  type:" + item.type);
//            WallPaper_Item item = new WallPaper_Item("2","22",WallpaperType.ONLINE,false,"http://img2.imgtn.bdimg.com/it/u=2445378982,1066541044&fm=23&gp=0.jpg","");
            try {
                synchronized (collectionMap) {
                    Wallpaper paper = new Wallpaper();
                    paper.setData(item.id, item.name, item.type, true, item.bigUrl, item.smallUrl);
                    paper.insert();
                    collectionMap.put(paper.id, paper);
                    LogUtils.d(tag, "addCollection  map size:" + collectionMap.size());
                }
                return true;
            } catch (Exception e) {
                LogUtils.d(tag, "addCollection error");
                e.printStackTrace();
            }
            return false;
        }

        private boolean deleteCollection(String param) {
            WallPaper_Item item = WallPaper_Item.parseJObject(param, WallPaper_Item.class);
//            WallPaper_Item item = new WallPaper_Item("2","22",WallpaperType.ONLINE,false,"http://img2.imgtn.bdimg.com/it/u=2445378982,1066541044&fm=23&gp=0.jpg","");
            try {
                synchronized (collectionMap) {
                    Wallpaper paper = new Wallpaper();
                    paper.delete(" id = ? ", item.id);
                    collectionMap.remove(item.id);
                    LogUtils.d(tag, "deleteCollection  map size:" + collectionMap.size());
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public ResultPackage call(Uri uri) {
            LogUtils.d(tag, "wallpaper_collection  uri:" + uri);
            String action = uri.getQueryParameter("action");
            String param = uri.getQueryParameter("param");
            LogUtils.d(tag, "wallpaper_collection  action:" + action + " param:" + param);
            RP_Boolean rp = new RP_Boolean();
            if (action != null && !action.equals("")) {
                if (action.equals("add")) {
                    rp.resource = addCollection(param);
                } else if (action.equals("delete")) {
                    rp.resource = deleteCollection(param);
                }
            }
            return rp;
        }
    };

    private ResourceHandler wallpaper_default = new ResourceHandler(this, "/wallpaper/default") {

        private WallPaper_Item getDefaultWallpaper() {
            String defaultPaper = "";
            try {
                defaultPaper = XServiceManager.getLiteConfigService().getStringValue("defaultwallpaper", "");
                LogUtils.d(tag, "getDefaultWallpaper  defaultPaper:" + defaultPaper);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            if (defaultPaper != null && !defaultPaper.equals("")) {
                WallPaper_Item item = WallPaper_Item.parseJObject(defaultPaper, WallPaper_Item.class);
                return item;
            }
            return null;
        }

        private boolean setDefaultWallpaper(String param) {
            if (param != null && !param.equals("")) {
                try {
                    WallPaper_Item item = WallPaper_Item.parseJObject(param, WallPaper_Item.class);
                    LogUtils.d(tag, "setDefaultWallpaper  tyep:" + item.type);
                    if (item.type.equals(OWNWALLPAPER)) {
                        boolean save = saveWallPaper(item.bigUrl.substring(FILE_PRE.length()));
                        if (save) {
                            item.bigUrl = FILE_PRE + WallPaperController.getInstance().getWallPaperPath();
                            item.smallUrl = FILE_PRE + item.bigUrl;
                            XServiceManager.getLiteConfigService().saveStringConfig("defaultwallpaper", item.toJSONString());
                            return true;
                        }
                        return false;
                    }
                    XServiceManager.getLiteConfigService().saveStringConfig("defaultwallpaper", param);
                    return true;
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        @Override
        public ResultPackage call(Uri uri) {
            String action = uri.getQueryParameter("action");
            String param = uri.getQueryParameter("param");
            if (action != null && !action.equals("")) {
                if (action.equals("get")) {
                    RP_WallpaperList rp = new RP_WallpaperList();
                    WallPaper_Item item = getDefaultWallpaper();
                    if (item != null)
                        rp.resource.add(item);
                    return rp;
                } else if (action.equals("set")) {
                    RP_Boolean rp = new RP_Boolean();
                    boolean setOk = setDefaultWallpaper(param);
                    rp.resource = setOk;
                    return rp;
                }
            }
            return null;
        }
    };

    private void initCollectionMap() {
        LogUtils.d(tag, "initCollectionMap");
        try {
            synchronized (collectionMap) {
                Wallpaper paper = new Wallpaper();
                List<LiteDBSupport> list = paper.selectAll();
                if (list != null && list.size() > 0) {
                    for (LiteDBSupport db : list) {
                        Wallpaper mWallpaper = (Wallpaper) db;
                        collectionMap.put(mWallpaper.id, mWallpaper);
                    }
                }
                LogUtils.d(tag, "initCollectionMap size:" + collectionMap.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<String> getScanPath() {
        List<Storage.SDevice> devicesList = Storage.getSDeviceList();
        List<String> list = new ArrayList<String>();
        if (devicesList != null && devicesList.size() > 0) {
            for (Storage.SDevice device : devicesList) {
                LogUtils.d(tag, "getScanPath  mount point:" + device.getMountPoint());
                list.add(device.getMountPoint());
            }
        }
        return list;
    }

    private synchronized boolean isPicture(String path) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        if (options.outHeight > 0 && options.outWidth > 0)
            return true;
        return false;
    }

    private synchronized void initOwnWallPaperList() {
        synchronized (ownWallPaperList) {
            ownWallPaperList.clear();
            List<String> list = getScanPath();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String path = list.get(i);
                    LogUtils.d(tag, "scanPhotoList!! path:" + path);
                    File rootDir = new File(path);
                    if (!rootDir.exists()) {
                        LogUtils.d(tag, "scanAPK---error path!!");
                        break;
                    }
                    if (!rootDir.isDirectory()) {
                        break;
                    } else {
                        String[] fileList = rootDir.list();
                        if (fileList != null && fileList.length > 0) {
                            for (int j = 0; j < fileList.length; j++) {
                                String basePath = rootDir.getAbsolutePath();
                                String subPath = basePath + "/" + fileList[j];
                                File sf = new File(subPath);
                                if (!sf.isDirectory()) {
                                    if (subPath.toLowerCase().endsWith(".png")
                                            || subPath.toLowerCase().endsWith(".jpg")
                                            || subPath.toLowerCase().endsWith(".bmp")
                                            || subPath.toLowerCase().endsWith(".jpeg")) {
                                        String filepath = sf.getAbsolutePath();
                                        int index = filepath.lastIndexOf("/");
                                        String name = filepath.substring(index);
//                                        LogUtils.d(tag, "scanPhoto---name:" + name + "  path:" + filepath);
                                        if (isPicture(filepath)) {
                                            WallPaper_Item data = new WallPaper_Item("", name, OWNWALLPAPER, false, FILE_PRE + filepath, FILE_PRE + filepath);
                                            ownWallPaperList.add(data);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    private void sendBroadcast(BroadcastAction.WALLPAPERCHANGED action, String param) {
        Intent i = new Intent();
        i.setAction(BroadcastAction.WALLPAPERCHANGEDBROASTCAST);
        i.putExtra("action", action.toString());
        i.putExtra("data", param);
        mContext.sendBroadcast(i);
        LogUtils.d("wall", "sendBroadcast!!");
    }

    @Override
    public void onStorageMounted(Storage.SDevice device) {
        LogUtils.d("wall", "onStorageMounted!! size:" + ownWallPaperList.size());
        initOwnWallPaperList();
        sendBroadcast(BroadcastAction.WALLPAPERCHANGED.EXTERNAL_ADD, String.valueOf(ownWallPaperList.size()));
    }

    @Override
    public void onStorageRemoved(Storage.SDevice device) {
        LogUtils.d("wall", "onStorageRemoved!! size:" + ownWallPaperList.size());
        initOwnWallPaperList();
        sendBroadcast(BroadcastAction.WALLPAPERCHANGED.EXTERNAL_REMOVE, String.valueOf(ownWallPaperList.size()));
    }

    private boolean saveWallPaper(String path) {
        String desPath = WallPaperController.getInstance().getWallPaperPath();
        LogUtils.d(tag, "path:" + path);
        LogUtils.d(tag, "desPath:" + desPath);
        File sourFile = new File(path);
        if (!sourFile.exists()) {
            LogUtils.d(tag, "savePhoto  file is miss");
            return false;
        }
        File desFile = new File(desPath);
        boolean success = FileUtils.copyFile(sourFile, desFile);
        LogUtils.d(tag, "success:" + success);
        if (success) {
            return true;
        } else {
            return false;
        }
    }
}
